package org.beanutopia.function;

import com.google.common.base.Function;
import com.google.common.base.Nullable;
import static com.google.common.base.ReferenceType.SOFT;
import static com.google.common.base.ReferenceType.STRONG;
import com.google.common.collect.ReferenceMap;

import java.util.Map;

/**
 * @author ymeymann
 * @since Nov 12, 2007 6:40:23 PM
 */
public class Cast<T> implements Function<Object,T> {
  final Class<T> clazz;
  private static final Map<Class<?>, Cast<?>> cast = new ReferenceMap<Class<?>, Cast<?>>(SOFT, STRONG);

  private Cast(Class<T> c) {
    clazz = c;
  }

  @SuppressWarnings({"unchecked"})
  public static <T> Cast<T> cast(Class<T> c) {
    Cast<T> res = (Cast<T>) cast.get(c);
    if (res == null) {
      cast.put(c, res = new Cast(c));
    }
    return res;
  }

  public T apply(@Nullable Object o) {
    return o == null ? null : clazz.cast(o);
  }
}
